//
//  CCDHaveRecTableView.m
//  operativeSide
//
//  Created by 王春程 on 16/5/19.
//  Copyright © 2016年 com.caocaod.www. All rights reserved.
//

#import "CCDHaveRecTableView.h"
#import "CCDHaveRecCell.h"
#import "MJRefreshHeader.h"
#import "MJRefreshFooter.h"
#import "HaveRecDataModels.h"


@interface CCDHaveRecTableView()<UITableViewDataSource,UITableViewDelegate>
@property (assign, nonatomic)               CGFloat firstLoc;
@property (strong, nonatomic)               NSMutableArray *dataArr;
@end

@implementation CCDHaveRecTableView

static NSString *identifier = @"haveRecCell";
static NSString *haveRecNoDataIdentifier = @"haveRecNoDataIdentifier";

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if(self = [super initWithFrame:frame style:style]) {
        [self registerClass:[CCDHaveRecCell class] forCellReuseIdentifier:identifier];
        [self registerClass:[NoDataCell class] forCellReuseIdentifier:haveRecNoDataIdentifier];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.backgroundColor = RGB(232, 232, 232);
//        [self addMJRefreshHeader:@selector(loadNewData)];
//        [self addMJRefreshFooter:@selector(loadMoreData)];
        self.delegate = self;
        self.dataSource = self;
    }
    return self;
}

#pragma mark - UpRefresh
//下拉刷新
- (void)loadNewData {
    [self.dataArr removeAllObjects];
    [self getPostDataWithLastId:@"0"];
}

#pragma mark - DownRefresh
//上拉获取
- (void)loadMoreData {
    if(self.dataArr.count == 0 || self.dataArr == nil) {
        [self getPostDataWithLastId:@"0"];
    } else {
        HaveRecJPieces *jpieces = [self.dataArr lastObject];
        NSString *lastIdString = jpieces.jPiecesIdentifier;
        [self getPostDataWithLastId:lastIdString];
    }
}

#pragma mark - UITableViewD
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if(self.dataArr.count == 0 || self.dataArr == nil) {
//        return 1;
//    } else {
//        return self.dataArr.count;
//    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(self.dataArr.count == 0 || self.dataArr == nil) {
//        return self.frame.size.height;
//    } else {
//        return 67 + 10;
//    }
    return 150;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(self.dataArr.count == 0 || self.dataArr == nil) {
//        NoDataCell *noDataCell = [tableView dequeueReusableCellWithIdentifier:haveRecNoDataIdentifier forIndexPath:indexPath];
//        switch (self.dataType) {
//            case DataTypeNoData:
//            {
//                noDataCell.noDataImage = [UIImage imageNamed:@"bag"];
//                noDataCell.tilString = @"暂无数据，下拉试试？";
//            }
//                break;
//            case DataTypeNoWifi:
//            {
//                noDataCell.noDataImage = [UIImage imageNamed:@"wifi"];
//                noDataCell.tilString = @"网络又调皮？下拉试试？";
//            }
//                break;
//            default:
//                break;
//        }
//        return noDataCell;
//    } else {
//        CCDHaveRecCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
//        HaveRecJPieces *piece = self.dataArr[indexPath.row];
//        cell.piece = piece;
//        return cell;
//    }
    CCDHaveRecCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    return cell;
}

//根据网络请求更新当前网络数据
- (void)getPostDataWithLastId:(NSString *)lastId {
    WS(weakSelf);
    NSString *baseUrl = @"http://serv.caocaod.com/work/couriers/ReceivedLists";
    
    //post参数
    NSDictionary *aesDic = @{
                             @"time" : [NSString getCurrentTime],
                             @"lastId" : lastId
                             };
    
    //字典转化成json字符串
    NSString *encString = [NSString getJsonStringWithDic:aesDic];
    //aes 加密json字符串
    NSData *praseData = [AESSecurityTool encryptAndBase64ToDataWithString:encString];
    //转码
    NSString *praseString = [[NSString alloc] initWithData:praseData encoding:NSUTF8StringEncoding];
    //拿到cookie
    NSDictionary *postDict;
    if(UserValue(@"cookie")) {
        NSDictionary *cookie = UserValue(@"cookie");
        postDict =  @{
                      @"verApp":[NSString getAppVer],
                      @"app":@"com.caocaod.work",
                      @"platform":@"iOS",
                      @"aes":praseString,
                      cookie[@"name"]:cookie[@"token"]
                      };
    } else {
        postDict =  @{
                      @"verApp":[NSString getAppVer],
                      @"app":@"com.caocaod.work",
                      @"platform":@"iOS",
                      @"aes":praseString
                      };
    }
    
    
    //开始网络请求
    [CCDHttpBaseTool postWithPath:baseUrl params:postDict progress:nil success:^(id JSON) {
        //JSON转化成字典
        NSDictionary *jsonDict  = JSON;
        if(1 == [jsonDict[@"result"] integerValue]) {
            NSString *aesString = jsonDict[@"aes"];
            //将返回的AES数据进行解析,解析成JSON字符串
            NSString *aesPrsaeString = [AESSecurityTool decryptAndBase64ToStringWithString:aesString];
            NSLog(@"aesStrig : %@",aesPrsaeString);
            //将JSON字符串解析成字典
            NSDictionary *newJsonDictionary = [NSDictionary dictionaryWithJsonString:aesPrsaeString];
            //保存COOkie
            NSDictionary *cookieDic = newJsonDictionary[@"cookie"];
            if(UserValue(@"cookie")) {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cookie"];
            }
            UserSetValueForKey(cookieDic, @"cookie");
            //如果解析AES的结果为1
             if(1 == [newJsonDictionary[@"result"] integerValue]) {
                HaveRecBaseClass *workModel = [[HaveRecBaseClass alloc] initWithDictionary:newJsonDictionary];
                [weakSelf.dataArr addObjectsFromArray:workModel.jPieces];
                if(weakSelf.dataArr.count == 0 && [lastId isEqualToString:@"0"]) {
                    weakSelf.dataType = DataTypeNoData;
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf reloadData];
                });
            } else {
                [weakSelf.dataArr removeAllObjects];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf reloadData];
                });
            }

        } else {
            if((-10 == [jsonDict[@"result"] integerValue])) {
                if(weakSelf.allIndex <= 2) {
                    [weakSelf createAesKey];
                    weakSelf.allIndex ++;
                } else {
                    [weakSelf makeToast:@"服务器错误，请稍候再试" duration:1.5 position:@"center"];
                    weakSelf.allIndex = 0;
                }
            }
        }
        [weakSelf.mj_header endRefreshing];
        [weakSelf.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [weakSelf makeToast:@"请检查您的网络" duration:1.5 position:@"center"];
        [weakSelf.dataArr removeAllObjects];
        self.dataType = DataTypeNoWifi;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf reloadData];
            
        });
        [weakSelf.mj_header endRefreshing];
        [weakSelf.mj_footer endRefreshing];
        
    }];
}

- (NSMutableArray *)dataArr {
    if(!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
